package com.fuerda.izb.view

import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.graphics.RectF
import android.util.AttributeSet
import androidx.constraintlayout.widget.ConstraintLayout
import com.fuerda.izb.R

class CustomRoundedCornerLayout @JvmOverloads constructor(
    context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0
) : ConstraintLayout(context, attrs, defStyleAttr) {

    private val backgroundPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
        style = Paint.Style.STROKE
    }
    private var hasShadow = true // 控制阴影开关的布尔变量

    init {
        val typedArray =
            context.obtainStyledAttributes(attrs, R.styleable.CustomRoundedCornerLayout)
        try {1
            backgroundPaint.strokeWidth =
                typedArray.getDimension(R.styleable.CustomRoundedCornerLayout_stroke_width1, 2f)
            backgroundPaint.color =
                typedArray.getColor(R.styleable.CustomRoundedCornerLayout_shadow_color1, Color.BLACK)
            val cornerRadius =
                typedArray.getDimension(R.styleable.CustomRoundedCornerLayout_corner_radius1, 8f)

            // 初始化阴影（可选，通常会在代码中动态控制）
            // setShadow(cornerRadius, typedArray.getColor(R.styleable.CustomRoundedCornerLayout_shadow_color, Color.BLACK))
        } finally {
            typedArray.recycle()
        }
    }

    fun setShadowEnabled(enabled: Boolean) {
        hasShadow = enabled
        invalidate() // 触发重绘以应用新的阴影状态
    }

    override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
        super.onSizeChanged(w, h, oldw, oldh)
        setupBackground()
    }

    private fun setupBackground() {
        backgroundPaint.strokeWidth /= 2 // 假设圆角半径等于线条宽度的一半
        if (hasShadow) {
            backgroundPaint.setShadowLayer(
                4f, // 阴影模糊半径
                2f,
                2f,
                backgroundPaint.color // 使用线条颜色作为阴影颜色，也可以独立定义
            )
        } else {
            backgroundPaint.clearShadowLayer()
        }
    }

    override fun onDraw(canvas: Canvas) {
        super.onDraw(canvas)

        val bounds = RectF(0f, 0f, width.toFloat(), height.toFloat())
        canvas.drawRoundRect(
            bounds,
            backgroundPaint.strokeWidth,
            backgroundPaint.strokeWidth,
            backgroundPaint
        )
    }
}